package edu.zjut.sjq.util;

import com.alibaba.fastjson.JSONObject;
import edu.zjut.sjq.bean.Article;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件操作工具类
 */
@Component
public class FileUtil {

	/**
	 * 图片上传
	 * 
	 * @return
	 * @throws FileUploadException
	 * @throws IOException
	 */
	public String uploadImg(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			String fileName = "";
			String newName = "";
			List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// 表单域
					String fieldName = item.getFieldName();
					String fieldValue = item.getString();
					System.out.println(fieldName + ": " + fieldValue);
				} else {
					// 文件域
					fileName = FilenameUtils.getName(item.getName());
					String extension = FilenameUtils.getExtension(item.getName());
					if (fileName!=null) {
                        newName = System.currentTimeMillis() + "." + extension;
						InputStream fileContent = item.getInputStream();
						File uploads = new File(PathUtil.imgPath);
						if (!uploads.exists()){
							uploads.mkdirs();
						}
                        File file = new File(uploads, newName);
						FileUtils.copyInputStreamToFile(fileContent, file);
					}
				}
			}
			//object.put("filename", fileName);
			//object.put("url",  PathUtil.imgPath + url);
			return newName;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}




	/**
	 * 文件下载
	 *
	 * @param filename
	 * @param realname
	 * @throws IOException
	 */
	public void downloadImg(String filename, String realname, HttpServletRequest request, HttpServletResponse response) {
		try {
			File file = new File(PathUtil.imgPath+ "/" + filename);
			FileInputStream inputStream = new FileInputStream(file);
			byte[] data = new byte[(int) file.length()];
			int length = inputStream.read(data);
			inputStream.close();
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
			response.setContentType("application/x-download");
			response.setContentLength(length);
			OutputStream stream = response.getOutputStream();
			stream.write(data);
			stream.flush();
			stream.close();
		} catch (Exception e) {
			e.printStackTrace();
			response.setStatus(404);
		}
	}
    /**
     * 显示图片
     *
     * @param filename
     * @throws IOException
     */
    public void showImg(String filename, HttpServletRequest request, HttpServletResponse response) {
        try {
            String extension = FilenameUtils.getExtension(filename);
            FileInputStream fis = null;
            response.setContentType("image/" + extension);
            OutputStream out = response.getOutputStream();
            File file = new File(PathUtil.imgPath + "/" + filename);
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
			e.printStackTrace();
            response.setStatus(404);
        }
    }


	/**
	 * 作品上传
	 *
	 * @return
	 * @throws FileUploadException
	 * @throws IOException
	 */
	public Article uploadArticle(HttpServletRequest request, HttpServletResponse response) {
		Article article = new Article();
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// 表单域
					String fieldName = item.getFieldName();
					String fieldValue = new String(item.getString().getBytes("iso-8859-1"),"UTF-8");
					System.out.println(fieldName + ": " + fieldValue);
					packageArticle(fieldName,fieldValue,article);
				} else {
					// 文件域
					String fileName = new String(FilenameUtils.getName(item.getName()).getBytes("iso-8859-1"),"UTF-8");
					String extension = FilenameUtils.getExtension(item.getName());
					String myName="";
					if (fileName!=null) {
						myName = System.currentTimeMillis() + "." + extension;
						File uploads;
						if (article.getCoverUrl()==null){
							uploads = new File(PathUtil.imgPath);
							article.setCoverUrl(PathUtil.accessImgUrl+myName);
						}else {
							uploads = new File(PathUtil.articlePath);
							article.setVideoUrl(PathUtil.accessArticleUrl+myName);
							article.setExtension(extension);
						}
						if (!uploads.exists()){
							uploads.mkdirs();
						}
						InputStream fileContent = item.getInputStream();
						File file = new File(uploads, myName);
						FileUtils.copyInputStreamToFile(fileContent, file);
					}
					// 包装

				}
			}
			return article;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}


	private void packageArticle(String fieldName,String fieldValue,Article article){
		if (article==null)
			article=new Article();

		if (fieldName.equals("title")){
			article.setTitle(fieldValue);
		}else if (fieldName.equals("description")){
			article.setDescription(fieldValue);
		}else if (fieldName.equals("type")){
			article.setType(Integer.parseInt(fieldValue));
		}else if (fieldName.equals("year")){
			article.setYear(Integer.parseInt(fieldValue));
		}else if (fieldName.equals("time")){
			article.setTime(fieldValue);
		}
	}


	/**
	 * 视频播放
	 */
	public void showVideo(String articleName, HttpServletRequest request, HttpServletResponse response) {
		try {
			String extension = FilenameUtils.getExtension(articleName);
			FileInputStream fis = null;
			response.setContentType("video/" + extension);
			OutputStream out = response.getOutputStream();
			File file = new File(PathUtil.articlePath + "/" + articleName);
			fis = new FileInputStream(file);
			byte[] b = new byte[fis.available()];
			fis.read(b);
			out.write(b);
			out.flush();
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.setStatus(404);
		}
	}



}
